# usage: make_umbrella.sh <filename> <pattern> <headerguard>
# eg: make_umbrella.sh fw.h fw/*.h FW_HEADER_H

# Creates a header file which just includes all headers in src/ (and obj/) which
# match the pattern specified (where the pattern is something like "fw/*.h".
# This is useful for keeping "umbrella" headers up-to-date, rather than having
# to track and edit them manually.
# NB: any header ending in '_impl.h' is not included in the umbrella header, as
# these headers are considered private to the fw library and not for client code.
# Users who need the functionality from an impl header can explicitly #include
# the header in question. We also exclude any headers with spaces (' ') in their
# filenames, as these can upset the build system later in the build process (as
# we use spaces to seperate each file in lists of files).


HEADER_FILE=$1
PATTERN=$2
HEADER_GUARD=$3
shift; shift; shift

# any remaining command line arguments are interpreted as a set of patterns to
# exclude any matching headers

EXCLUDE_PATTERN=$*

# The header file name as it would be used in a #include (i.e. remove src/ or
# obj/ from the start of the filename). This is always present in the exclude
# pattern, as we don't want the header to include itself!
HEADER_SPEC=`echo $HEADER_FILE | sed -e 's~^\(src\|obj\)/~~'`


if [ -z "$EXCLUDE_PATTERN" ];then
    EXCLUDE_PATTERN=$HEADER_SPEC; else
    # surround the EXCLUDE_PATTERN in \( \), and replace the spaces with \|, to
    # create a sed-compatible regex which matches any of the specified filenames.
    #   (eg 'a b c' would convert to '\(a\|b\|c\)'
    EXCLUDE_PATTERN=`echo "$HEADER_SPEC $EXCLUDE_PATTERN" |
        sed -e's~ ~\\\\|~g' -e 's~.*~\\\\(&\\\\)~'`;
fi

echo "/// \\\\file" >> $HEADER_FILE
echo "/// \\\\brief Autogenerated umbrella header matching \"$PATTERN\"" >> $HEADER_FILE
echo "#ifndef $HEADER_GUARD" >> $HEADER_FILE
echo "#define $HEADER_GUARD" >> $HEADER_FILE

# sed to the rescue once again!
ls -1 src/$PATTERN | \
    sed -e 's~.*_impl\.h.*~~' \
        -e "s~.*$EXCLUDE_PATTERN.*~~" \
        -e 's~src/\(.*\)~#include "\1"~' \
        -e 's~.*".* .*".*~~' \
        >> $HEADER_FILE

# this should include autogen headers (in obj/) too (should any exist)...
ls -1 obj/$PATTERN | \
    sed -e 's~.*_impl\.h.*~~' \
        -e "s~.*$EXCLUDE_PATTERN.*~~" \
        -e 's~obj/\(.*\)~#include "\1"~' \
        -e 's~.*".* .*".*~~' \
        >> $HEADER_FILE

echo "#endif//$HEADER_GUARD" >> $HEADER_FILE


